﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm1.data_access
{
    internal class BackendClient
    {
        private HttpClient httpClient;

        /// <summary>
        /// 创建httpclient实例，定义 baseURL
        /// </summary>
        public BackendClient() 
        {
            httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri("http://localhost:8080/");
        }

        /// <summary>
        ///     发送请求，获得响应数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<Dictionary<String, Object>> SendRequest(String url, HttpMethod method, Object data)
        {
            try
            {
                //构造请求
                var request = new HttpRequestMessage(method, url);
                //post请求
                if (method.Method.Equals(HttpMethod.Post.Method, StringComparison.OrdinalIgnoreCase))
                {
                    //将要传递的数据转换为json字符串
                    var jsonData = JsonConvert.SerializeObject(data);
                    request.Content = new StringContent(jsonData, System.Text.Encoding.UTF8, "application/json");
                }
                var response = await httpClient.SendAsync(request);     //发送请求并获取响应
                response.EnsureSuccessStatusCode();     //确保请求成功
                var responseContent = await response.Content.ReadAsStringAsync();
                Dictionary<String,Object> resp = JsonConvert.DeserializeObject<Dictionary<String, Object>>(responseContent);
                return resp;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请求异常：" + ex.Message,"异常");
                return null;
            }
        }
    }
}
